#ifndef USER_H
#define USER_H

#include "m_fhs.h"
#include <head/m_message.h>
#include <support/mysql_helper.h>

struct User
{
    int id=0;
    QString account="NULL";
    QString passwd="NULL";
    QString roles="NULL";
    bool needSave=false;

    void awake()
    {
        QSettings reg(REG_KEY,QSettings::NativeFormat);
        int flag=reg.value("save_flag").toInt();
        if(flag == 1)
        {
            needSave=true;
            id=reg.value("user_id").toInt();
            account=reg.value("user_account").toString();
            passwd=reg.value("user_passwd").toString();
            roles=reg.value("user_roles").toString();
        }
    }

    void saveFlag()
    {
        QSettings reg(REG_KEY,QSettings::NativeFormat);
        if(needSave)
            reg.setValue("save_flag",1);
        else
            reg.setValue("save_flag",0);
    }

    void saveInfo()
    {
        QSettings reg(REG_KEY,QSettings::NativeFormat);
        reg.setValue("user_id",id);
        reg.setValue("user_account",account);
        reg.setValue("user_passwd",passwd);
        reg.setValue("user_roles",roles);
    }

    QString genPasswd(const QString &passwd)
    {
        auto result=QCryptographicHash::hash(passwd.toLatin1(),
                                             QCryptographicHash::Md5).toHex();
        return result;
    }

    bool checkLoginInfo()
    {
        bool result=false;
        {
            QSqlDatabase db=getConnection(OA_HOST,OA_PORT,
                                          OA_USER,OA_PASSWD,
                                          OA_DBNAME,SQL_OA_CONNECTION);
            if(db.open())
            {
                QSqlQuery query(db);
                query.exec(QString("select id,password from think_user where account='%1'")
                           .arg(account));
                if(query.next())
                {
                    id=query.value(0).toInt();
                    auto password=query.value(1).toString();
                    if(password == genPasswd(passwd))
                        result=true;
                }

                if(id != 0)
                {
                    query.exec(QString("select role_id from think_role_user where user_id='%1'").arg(id));
                    QStringList items;
                    while (query.next()) {
                        items.append(QString::number(query.value(0).toInt()));
                    }
                    roles = items.join(",");
                }

                saveInfo();
                db.close();
            }
            else {
                QMessageBox::warning(0,"警告","无法连接数据库，无法继续操作！");
                qDebug() << db.lastError().text();
            }

        }
        QSqlDatabase::removeDatabase(SQL_OA_CONNECTION);

        return result;
    }
};

#endif // USER_H
